/**
 * 网络请求处理
 */
var _json = require('json_helper.js')
var comm = require('comm_util.js')
var config = require('config/Nconfig.js')
var ckcrypt = require('CKCrypto.js')
const SUCCESS_STATUS = 200
var requestTask = null
let app = getApp();
/**
 * 构建请求头
 */
function buildHttpHeader() {
  var header = {
    'content-type': 'application/json',
  }
  return header
}

function buidJsonObject(map) {
  let obj = Object.create(null);
  for (let [k, v] of map) {
    obj[k] = v;
  }
  return obj
}

function getStorage(key) {
  var flag = false;
  var val = null;
  while (!flag) {
    try {
      val = wx.getStorageSync(key);
      flag = true;
    } catch (e) {

    }
  }
  return val;
}
/**
 * 开始请求
 */
function request(url, map_params, methodType, showLoading,success, fail) {
  if (showLoading){
    wx.showLoading({
      title: '请稍等...',
      mask: true,
      icon: 'loading'
    })
  }
  var pages = getCurrentPages()
  var currentPage = pages[pages.length - 1] //获取当前页面的对象
  var url1 = currentPage.route //当前页面url
  var token = wx.getStorageSync("userToken")
  //获取不需要登入过滤的接口
  var whiteList = config.getWhiteFun()
  var exitFlag = whiteList.includes(url.split('/')[1])
  if ((token != null && typeof (token) != undefined && token.length > 0) || exitFlag == true || url1 == "pages/website-official/website") {
    map_params.set('deviceId', wx.getStorageSync("UUID"))
    map_params.set("timestamp", Date.parse(new Date()))
    map_params.set("token", wx.getStorageSync("userToken"))
    var sign = ckcrypt.sign(map_params)
    map_params.set("signature", comm.hexTobase64(sign))
    var _jsondata = _json.stringToJson(_json.mapToJson(map_params))
    if (config.debug) {
      console.log("request->_url=", url)
      console.log("request->_jsondata=", _jsondata)
    }
    requestTask = wx.request({
      url: config.getHost() + url,
      method: methodType,
      data: _jsondata,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'apiVersion': '1.1'
      },
      success: function(response) {
        //{data: {…}, header: {…}, statusCode: 405, errMsg: "request:ok"}
        wx.hideLoading()
        if (config.debug) {
          console.log("networks-->request-->success")
          console.log(response)
        }
        if(url1 != "pages/website-official/website"){
        if (response.statusCode == SUCCESS_STATUS) {
          if (response.data.responseCode == "00000") {
            success(response.data.data)
          } else if (response.data.responseCode == '1001') { //登入超时
            exchangeToken()
          } else {
            fail(response.data.responseCode, response.data.errMessage)
          }
        } else {
          fail("10011", response)
        }
        }
      },
      fail: function(error) {
        wx.hideLoading()
        if (config.debug) {
          console.log("networks-->request-->fail")
          console.log(error)
        }
        if (comm.isFunctinMethod(fail)) {
          fail("10011", fail.errMsg)
        }
      },
      complete: function() {
        requestTask = null
      }
    })
  } else {
    wx.reLaunch({
      url: "/pages/login/login",
    })
  }

}

function exchangeToken() {
  var params = new Map()
  params.set('phone', wx.getStorageSync("phone"))
  _post("account/updateToken.do", params, function(success) {
    if (config.debug) {
      console.log("has update token...%o", success)
    }
    wx.setStorage({
      key: 'userToken',
      data: success.token,
    })
  }, function(errorCode, errMsg) {
    wx.reLaunch({
      url: "/pages/login/login",
    })
  });
}
/**
 * 取消请求
 */
function _cancleReqest() {
  if (requestTask != null) {
    requestTask.abort()
  }
}
/**
 * post请求。
 * url:请求地址。
 * map_params：请求参数，map数据格式。
 * success：成功回调（数据正常，状态为200才回调）。
 * fail：失败或者错误回调（状态 200以外或者网络错误）。
 */
function _post(url, map_params, success, fail) {
  request(url, map_params, "POST", true,success, fail)
}
function _postNoLoading(url, map_params, success, fail) {
  request(url, map_params, "POST", false,success, fail)
}
/**
 * get请求
 */
function _get(url, map_params, success, fail) {
  request(url, map_params, "GET", true,success, fail)
}
function _getNoLoading(url, map_params, success, fail) {
  request(url, map_params, "GET", false,success, fail)
}
//暴露方法
module.exports = {
  requestPost: _post,
  requestPostNoLoading: _postNoLoading,
  requestGetNoLoading: _getNoLoading,
  requestGet: _get,
  cancleReqest: _cancleReqest
}